package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //获取开始和结束的日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //将当前日期新增一天，加入列表集合
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 通过日期列表查询每一天的营业额,并封装到一个列表中
        List<Double> turnovers = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //获取当天开始时刻，和当天最晚时刻
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            // select sum(amount) from orders where order_time > ? and order_time < ? and status = 5;
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnovers.add(turnover);
        }

        //根据数据响应格式，将对象转换成字符串
        String dateStr = StringUtils.join(dateList, ",");
        String turnoversStr = StringUtils.join(turnovers, ",");


        //封装数据返回给前端
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(dateStr)
                .turnoverList(turnoversStr)
                .build();

        return turnoverReportVO;
    }

    /**
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //获取开始日期和结束日期之间的日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //查询每天新增的用户，并加入到集合中，并统计总用户数加入到集合
        List<Integer> userNumList = new ArrayList<>();
        List<Integer> userTotalList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //获取当前开始时间和结束时间
            LocalDateTime beginDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //查询在此之前所有的用户（没有开始时间）
            Integer userTotal = userMapper.getByDate(null, endDateTime);
            userTotalList.add(userTotal);

            //查询当前新增的用户数量
            Integer userNum = userMapper.getByDate(beginDateTime, endDateTime);
            userNumList.add(userNum);
        }
        //将三个集合分别转换成字符串,封装到UserReportVO,返回给前端
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(userNumList, ","))
                .totalUserList(StringUtils.join(userTotalList, ","))
                .build();
        return userReportVO;
    }

    /**
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //获取开始日期和结束日期之间的日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //通过开始时间和结束时间获取每天的订单总数和有效订单数（status==5）
        List<Integer> orderCountList = new ArrayList<>();//订单列表
        List<Integer> validOrderCountList = new ArrayList<>();//有效订单列表
        Integer orderCountSum = 0;//订单数量总计
        Integer validOrderCountSum = 0;//有效订单总计
        Double orderCompletionRate = 0.0;
        for (LocalDate localDate : dateList) {
            //获取对当天的开始时刻和结束时刻
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询当前所有订单数量以及查询当天所有的有效订单数加入到集合
            Integer orderCount = orderMapper.getByDateAndStatus(beginTime, endTime, null);
            Integer validOrderCount = orderMapper.getByDateAndStatus(beginTime, endTime, Orders.COMPLETED);
            //将查询的数据加入集合并进行累加统计
            orderCountList.add(orderCount);
//            orderCountSum += orderCount;
            validOrderCountList.add(validOrderCount);
//            validOrderCountSum += validOrderCount;
        }
        //将查询的结果进行累加
        orderCountSum = orderCountList.stream().reduce(Integer::sum).get();
        validOrderCountSum = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        if (orderCountSum != 0) {
            orderCompletionRate = (validOrderCountSum * 1.0) / orderCountSum;
        }

        //封装成OrderReportVO集合返回给前端
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(orderCountSum)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .validOrderCount(validOrderCountSum)
                .build();
        return orderReportVO;
    }

    /**
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO Top10(LocalDate begin, LocalDate end) {
        //获取开始日期的开始时刻和结束日期的结束时刻
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

//        //根据开始时间和结束时间以及状态查询orders和order_detail，返回商品名称和商品数量
//        List<Map<String,Integer>> mapList = orderMapper.getTop10Count(beginTime,endTime,Orders.COMPLETED);
//
//        //从List<Map>中取出商品品名称和销量，分别封装到列表中
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
//        for (Map<String, Integer> map : mapList) {
//            nameList.add(String.valueOf(map.get("name")));
//            numberList.add(String.valueOf(map.get("nameNum")));
//        }

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10Count(beginTime, endTime, Orders.COMPLETED);
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(String.valueOf(goodsSalesDTO.getNumber()));
        }

        //将数据封装成json字符串返回给前端
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return salesTop10ReportVO;
    }

    @Override
        public void exportBusinessData(HttpServletResponse response){
        //获取开始日期和结束日期（昨天为截止时间）
        LocalDate endDate = LocalDate.now().minusDays(1);//获取昨天的日期
        LocalDate beginDate = LocalDate.now().minusDays(30);//获取30天之前的前一天的日期

        //查询总数据
        LocalDateTime beginTime = LocalDateTime.of(beginDate,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate,LocalTime.MAX);
        BusinessDataVO businessDataLast30 = workspaceService.getBusinessData(beginTime, endTime);

        // 查询明细数据
        List<LocalDate> dateList = new ArrayList<>();//日期列表
        List<BusinessDataVO> businessDataDetailList = new ArrayList<>();//运营数据明细表
        //由于已经确定是30填了，所以直接使用for循环30次，不用感觉很low，合适才是一切。
        for (int i = 0; i < 30; i++) {
            //将当前日期加入列表
            dateList.add(beginDate);
            //获取当天开始时刻和结束时刻
            LocalDateTime begin = LocalDateTime.of(beginDate,LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(beginDate,LocalTime.MAX);
            //将当天的运营数据加入明细表
            businessDataDetailList.add(workspaceService.getBusinessData(begin, end));
            beginDate = beginDate.plusDays(1);
        }

        try {
            //创建文件输入流：文件资源->内存（java程序中）
            InputStream in = this.getClass()
                    .getClassLoader()
                    .getResourceAsStream("template/businessDataReportTemplate.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");


            insertToExcel(sheet, beginDate, endDate, businessDataLast30, dateList, businessDataDetailList);

            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            in.close();
            excel.close();
            out.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    private static void insertToExcel(XSSFSheet sheet, LocalDate beginDate, LocalDate endDate, BusinessDataVO businessDataLast30, List<LocalDate> dateList, List<BusinessDataVO> businessDataDetailList) {
        //填充第二行
        sheet.getRow(1).getCell(1).setCellValue("时间："+ beginDate +"至"+ endDate);
        //填充第四行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessDataLast30.getTurnover());
        row.getCell(4).setCellValue(businessDataLast30.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDataLast30.getNewUsers());
        //填充第五行
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessDataLast30.getValidOrderCount());
        row.getCell(4).setCellValue(businessDataLast30.getUnitPrice());

        //填充明细表
        int[] index = {7,1};
        for (int i = 0; i < dateList.size(); i++) {
            row = sheet.getRow(index[0]);
            row.getCell(index[1]++).setCellValue(String.valueOf(dateList.get(i)));
            row.getCell(index[1]++).setCellValue(String.valueOf(businessDataDetailList.get(i).getTurnover()));
            row.getCell(index[1]++).setCellValue(String.valueOf(businessDataDetailList.get(i).getValidOrderCount()));
            row.getCell(index[1]++).setCellValue(String.valueOf(businessDataDetailList.get(i).getOrderCompletionRate()));
            row.getCell(index[1]++).setCellValue(String.valueOf(businessDataDetailList.get(i).getUnitPrice()));
            row.getCell(index[1]).setCellValue(String.valueOf(businessDataDetailList.get(i).getNewUsers()));
            index[0]++;
            index[1] = 1;
        }
    }

}
